package easy;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    public static void main(String[] args) {
        int target = 9;
        Solution2.twoSum(new int[]{2, 7, 11, 15}, target);

        int[] result= Solution2.twoSum(new int[]{2, 7, 11, 15}, 9);

        // 输出结果
        System.out.println("第" + result[0] + " 个和第 " + result[1] + " 个元素之和为 " + target);
    }


    public static class Solution2 {
        public static int[] twoSum(int[] nums, int target) {
            int len = nums.length;
            Map<Integer, Integer> hashMap = new HashMap<>(len - 1);
            hashMap.put(nums[0], 0);
            for (int i = 1; i < len; i++) {
                int another = target - nums[i];
                if (hashMap.containsKey(another)) {
                    return new int[]{hashMap.get(another),i};
                }
                hashMap.put(nums[i], i);
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    }
}
